package com.yq.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yq.constant.MenuConstants;
import com.yq.domain.SysMenu;
import com.yq.mapper.SysMenuMapper;
import com.yq.mapper.SysUserMapper;
import javafx.scene.layout.Background;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements IService<SysMenu> {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询权限和菜单所有节点
     *
     * @return
     */


    public List<SysMenu> selectMenu(String userId) {
        String menu = redisTemplate.opsForValue().get(MenuConstants.MENU_PREFIX + userId);
        List<SysMenu> menuList = null;
        if (StringUtils.hasText(menu)) {
            //转成集合
            menuList = JSON.parseArray(menu, SysMenu.class);
        }
        menuList = sysMenuMapper.selectByUserId(Long.valueOf(userId));
        if (!CollectionUtils.isEmpty(menuList)) {
            redisTemplate.opsForValue().set(MenuConstants.MENU_PREFIX + userId, JSON.toJSONString(menuList), Duration.ofDays(7));
        }

        return transformMenu(menuList, 0L);
    }

    private List<SysMenu> transformMenu(List<SysMenu> menuList, long pid) {
        //知道菜单深度时可以循环 不知道时可以递归
        //拿到父节点
//        List<SysMenu> root = menuList.stream()
//                .filter(r -> r.getParentId().equals(pid)).
//                collect(Collectors.toList());
//        root.forEach(r->{
//            List<SysMenu> collect = menuList.stream()
//                    .filter(f -> f.getParentId().equals(r.getMenuId()))
//                    .collect(Collectors.toList());
//            r.setMenuList(collect);
//        });
        //递归
        List<SysMenu> root = menuList.stream()
                .filter(r -> r.getParentId().equals(pid)).
                        collect(Collectors.toList());
        root.forEach(r -> {
            r.setMenuList(transformMenu(menuList, r.getMenuId()));
        });
        return root;
    }


}
